var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require("express-session")

//引入工具类
var jwtUtil = require('./utils/jwtUtil')


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');


//配置中间件 maxAge单位为ms
app.use(session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: ('name', 'value',{maxAge:  5*60*1000,secure: false})
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

global.globalKey ="123456"

//jwt 拦截器
app.use(async function(req,resp,next){
    let path =req.path

    if (path.startsWith("/users/login") || path.startsWith("/users/regist")) {
        next()
        return
    }
        // 从请求头里头拿到令牌
        let token = req.headers.token
        if (!token) {
            token =req.query.token
        }


    let result =await jwtUtil.verifyasync( token,globalKey)

    if (result.err){
        resp.status(500)
        resp.send("会话已过期，请重新登录，前端的表现通常是直接重定向到登录页")
    }else{
        req.headers.session=result
        next();
    }


})


app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  //改写异常状态500
   res.status(500)
   res.send(err.message)
});

module.exports = app;
